# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""x3d utils"""
import logging
from mindspore import Tensor
import mindspore.ops as ops


def get_logger(name):
    """
    Retrieve the logger with the specified name or, if name is None, return a
    logger which is the root logger of the hierarchy.
    Args:
        name (string): name of the logger.
    """
    return logging.getLogger(name)


logger = get_logger(__name__)


def round_width(width, multiplier, min_width=1, divisor=1, verbose=False):
    """ Round width of filters based on width multiplier """
    if not multiplier:
        return width
    width *= multiplier
    min_width = min_width or divisor
    if verbose:
        logger.info("min width %d", min_width)
        logger.info("width %d divisor %d", width, divisor)
        logger.info("other %f", int(width + divisor / 2) // divisor * divisor)

    width_out = max(min_width, int(width + divisor / 2) // divisor * divisor)
    if width_out < 0.9 * width:
        width_out += divisor
    return int(width_out)


def drop_path(x: Tensor, drop_prob: float = 0.0, training: bool = False):
    """
    Stochastic Depth per sample.
    """
    if drop_prob == 0.0 or not training:
        return x
    keep_prob = 1 - drop_prob
    shape = (x.shape[0],) + (1,) * (
        x.ndim - 1
    )  # work with diff dim tensors, not just 2D ConvNets
    uniformreal = ops.UniformReal()
    mask = keep_prob + uniformreal(shape)
    # binarize
    floor = ops.Floor()
    mask = floor(mask)
    div = ops.Div()
    output = div(x, keep_prob) * mask
    return output
